package com.niezhiliang.netty.websocket.spring.boot.demo.service.other.handler;

import com.niezhiliang.netty.websocket.spring.boot.demo.service.SocketServer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;


@Component
public class UdpServerHandler extends SimpleChannelInboundHandler<DatagramPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) {
        ByteBuf buf = msg.content();

        String hexDump = ByteBufUtil.hexDump(buf);
        System.out.println("hexDump:"+hexDump);

        // 将接收到的字节数据转换为16进制字符串
        StringBuilder hexString = new StringBuilder();
        while (buf.isReadable()) {
            hexString.append(String.format("%02X ", buf.readByte()));
        }
        String receivedHexMessage = hexString.toString().trim();
        System.out.println("Received UDP message in hex: " + receivedHexMessage);

        // 在这里处理接收到的16进制消息，比如进行业务逻辑处理

        // 将16进制字符串转换为字节数据，用于回复消息
        byte[] responseBytes = hexStringToByteArray(receivedHexMessage);

        // 发送回复消息到客户端
        ctx.writeAndFlush(new DatagramPacket(ctx.alloc().buffer().writeBytes(responseBytes), msg.sender()));

        SocketServer.sendAll(receivedHexMessage);
    }

    // 将16进制字符串转换为字节数组
    private byte[] hexStringToByteArray(String hexString) {
        hexString = hexString.replaceAll("\\s+", ""); // 去掉空格
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}


